﻿using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Reflection;
using Castle.Core;
using Castle.MicroKernel.Registration;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Embedded;
using Raven.Client.Indexes;
using Topics.Radical.Helpers;

namespace Milestone.Boot.Installers
{
	/// <summary>
	/// A Windsor installer.
	/// </summary>
	[Export( typeof( IWindsorInstaller ) )]
	public class RavenDBInstaller : IWindsorInstaller
	{
		/// <summary>
		/// Performs the installation in the <see cref="T:Castle.Windsor.IWindsorContainer"/>.
		/// </summary>
		/// <param name="container">The container.</param>
		/// <param name="store">The configuration store.</param>
		public void Install( Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store )
		{
			container.Register
			(
				Component.For<IDocumentStore>()
					.UsingFactoryMethod( () =>
					{
						var commandLine = CommandLine.GetCurrent();
						
						String dataDirectory;
						if( !commandLine.TryGetValue( "DataDir", out dataDirectory ) ) 
						{
							var userPath = Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData );
							userPath = Path.Combine( userPath, "Milestone", "1.0.0.0", "Data" );
							dataDirectory = userPath;
						}

						var documentStore = new EmbeddableDocumentStore()
						{
							DataDirectory = dataDirectory,
							UseEmbeddedHttpServer = commandLine.Contains( "ws" )
						};
						
						documentStore.Initialize();

						//index setup
						IndexCreation.CreateIndexes( Assembly.GetExecutingAssembly(), documentStore );

						return documentStore;
					} )
					.LifeStyle.Is( LifestyleType.Singleton )
			);
		}
	}
}